package com.he.consumer;

import com.he.constant.RabbitmqConstant;
import com.he.constant.RedisConstant;
import com.he.domain.dto.ArticleViewMessage;
import com.he.domain.vo.ArticleConditionVO;
import com.he.service.RedisService;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author He
 * @version 1.0
 * @Date 2023/9/19 15:31
 * @Desc 浏览量消费者
 */
@Service
public class RedisSyncConsumer {
    @Resource
    private RedisService redisService;


    @RabbitListener(queues = RabbitmqConstant.ARTICLE_VIEW_QUEUE)
    public void listenArticleViewQueue(@Payload ArticleViewMessage articleViewMessage) {
        System.out.println("------监听到了文章浏览量队列------");
        redisService.incrZet(RedisConstant.ARTICLE_VIEW_COUNT,articleViewMessage.getArticleId().toString()
                ,(double) articleViewMessage.getIncrement());
        Object redisObject = redisService.getHash(RedisConstant.TAG_ARTICLE_LIST, articleViewMessage.getArticleId().toString());
        List<ArticleConditionVO> articleConditionVOS = Collections.emptyList();
        if (redisObject instanceof List<?> && !((List<?>) redisObject).isEmpty() && ((List<?>) redisObject).get(0) instanceof ArticleConditionVO) {
            articleConditionVOS = (List<ArticleConditionVO>) redisObject;
            // 执行操作
            articleConditionVOS = articleConditionVOS.stream().map(
                    articleConditionVO -> {
                        articleConditionVO.setArticleViews(articleConditionVO.getArticleViews() + articleViewMessage.getIncrement());
                        return articleConditionVO;
                    }
            ).collect(Collectors.toList());
            redisService.setHash(RedisConstant.TAG_ARTICLE_LIST, articleViewMessage.getArticleId().toString(), articleConditionVOS);
        } else {
            // 处理对象不是 List<ArticleConditionVO> 的情况
        }
    }

    @RabbitListener(queues = RabbitmqConstant.ARTICLE_CACHE_QUEUE)
    public void listenArticleCacheQueue(){
        System.out.println("------监听到了文章缓存队列------");
        redisService.deleteObject(RedisConstant.TAG_ARTICLE_LIST);
        redisService.deleteObject(RedisConstant.CATEGORY_ARTICLE_LIST);
        redisService.deleteObject(RedisConstant.HOME_ARTICLE_LIST);
        redisService.deleteObject(RedisConstant.SITE_CONFIG_KEY);
    }
}
